package win.devhu.onestation.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import io.javalin.Javalin;
import io.javalin.apibuilder.ApiBuilder;
import win.devhu.onestation.controller.IndexController;
import win.devhu.onestation.controller.LoginController;

public class Router extends ApiBuilder {

	@Inject
	private Javalin app; // 依赖注入

	@Inject
	private IndexController indexController;

	private Logger logger = LoggerFactory.getLogger(ApplicationModule.class);

	/**
	 * 路由绑定
	 */
	public void bindRoutes() {

		// 接口相关
		app.routes(() -> {

			before(LoginController.ensureLoginBeforeViewing); // 未登录强制跳转

			// 页面相关
			get("/", ctx -> ctx.redirect("/index"));
			get("/index", ctx -> ctx.render("templates/index.html"));
			get("/otherpage", ctx -> ctx.render("templates/other.html"));
			get("/login", ctx -> ctx.render("templates/login.html"));

			// 接口服务
			path("/api", () -> {

				// dt 工具相关
				path("/dt", () -> {
					// sayhello 示例程序 非 Controller Handler 方式调用
					post("/sayhello", ctx -> { // 定义接口路径
						String uname = ctx.formParam("uname"); // 获取表单传递的参数
						ctx.result(indexController.sayHello(uname)); // 返回接口调用返回
					});
				});

				// 登录接口
				path("/user", () -> {
					post("/signin", LoginController.handleSigninPost);
					post("/signup", LoginController.handleSignupPost);
					post("/logout", LoginController.handleLogoutPost);
					get("/entrylog", LoginController.handleEntryLogGet);
				});
			});
		});

		// 错误页面统一处理
		app.error(404, ctx -> {
			ctx.render("templates/404.html");
			logger.error("404 错误，页面路径:" + ctx.path());
		});

	}
}
